﻿using BackendLogic;
using BackendLogic.BaseLogic;
using BackstageWeb.App_Start.Helper;
using ComTools.Extensions;
using ComTools.Map;
using Ioc.Unity;
using MappingDTO.Admin;
using System;
using System.Web.Mvc;
using ToolsModel;

namespace BackstageWeb.Areas.Admin.Controllers
{
    public class LoginController : BaseController
    {
        // GET: Admin/Login
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            string code = ValidateCode.CreateValidateCode(4);
            Session["ValidateCode"] = code;
            byte[] bytes = ValidateCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }

        ///</summary>
        ///登录
        ///</summary>
        public ContentResult LoginCheck()
        {
            var resultInfo = new ResultJsonInfo<AdminTicket>();
            try
            {
                //实体接收数据
                var parametersInfo = DeserializeRequestData<ParametersInfo<LoginReqDTO>>(requestInfo);
                //实体数据验证
                parametersInfo.Validate(parametersInfo.ObjectToDic());

                ISysUserService sysUser = UnityCIContainer.Instance.GetService<ISysUserService>();
                //验证码验证
                if (Session["ValidateCode"] != null)
                {
                    if (Session["ValidateCode"].ToString() == parametersInfo.parameters.sVialdCode)
                    {
                        //数据库验证
                        resultInfo = sysUser.UserLogin(parametersInfo.parameters);

                        if (resultInfo != null && resultInfo.Code == 1)//验证通过
                        {
                            if (resultInfo.Success)
                            {
                                UserSession.AddLoginUser(resultInfo.Data);
                            }
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "验证码不正确！";
                    }
                }
                else
                {
                    resultInfo.Msg = "验证码失效，请重新获取！";
                }
            }
            catch (Exception ex)
            {
                resultInfo.Success = false;
                resultInfo.ErrMsg = ex.Message;
                resultInfo.Msg = ex.Message;
            }
            return ReturnResult(resultInfo, resultInfo.ErrMsg);
        }
    }
}